﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using Contacts.Data.Data;

namespace Contacts.Web
{
    public partial class PersonEditor : BasePage
    {
        private string _appconfConnString = ConfigurationManager.AppSettings["DatabaseConnection"];
        private ContactsDataPersons _dataPersons = new ContactsDataPersons();
        private ContactsDataGroups _dataGroups = new ContactsDataGroups();

        protected override void PageLoad()
        {
           lblPersonID.Text = Request.QueryString["PersonID"];
            if (!IsPostBack)
            {
                ShowPersonInfo();
            }

        }

        protected void BtnSavePhotoClick(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;

            string fileName = Path.GetFileName(ImageUpload.PostedFile.FileName);
            // Скомбинировать целевой каталог с именем файла.
            string destPath = Path.Combine(@"C:\Images\", fileName);

           if (File.Exists(destPath))
           {
              lblCheckGroups.Text = "Warning! - Файл с таким именем уже существует!";
           }
           else
           {
              // Сохранить файл на сервере.
              ImageUpload.PostedFile.SaveAs(destPath);

              lblNewPhoto.Text = fileName; // НАЗВАНИЕ КАРТИНКИ (Должно ухадить в базу)
              imgPhoto.ImageUrl = @"GetImage.aspx?file=" + fileName;
           }
        }

        protected void BtnSaveClick(object sender, EventArgs e)
        {
           if(!Page.IsValid) return;

            int idOfCurrentPerson;
            string rowFirstName = ttFirstName.Text;
            string rowLastName = ttLastName.Text;
            string rowPhone = Regex.Replace(ttPhone.Text, @"[^\d]", ""); // Отчищаем телефон от других символов перед отправкой в BD
            string rowEmail = ttEmail.Text;
            string rowBirthday = ttDatePicker.Text;
            int validGroupID;

            if (lblPersonID.Text == "")
            {
                idOfCurrentPerson = 0;
            }
            else
            {
                idOfCurrentPerson = Convert.ToInt32(lblPersonID.Text);
            }

            string rowPhoto = lblNewPhoto.Text;
            if (lblNewPhoto.Text.Length < 3) rowPhoto = lblPath.Text;
            if ((lblPath.Text != "Default.png") && (lblNewPhoto.Text != ""))
            {
               File.Delete("C:\\Images\\" + lblPath.Text);
            }

            int groupID = Convert.ToInt32(ddGroupList.SelectedValue);
            validGroupID = groupID;

            _dataPersons.SavePerson(idOfCurrentPerson, rowFirstName, rowLastName, rowPhone, rowEmail, rowBirthday, rowPhoto, validGroupID);

            
            Response.Redirect("PersonList.aspx");
        }

        protected void BtnCancelClick(object sender, EventArgs e)
        {
           //TODO: Отменять применение картинки!!!

           if ((lblNewPhoto.Text != lblPath.Text) && (lblNewPhoto.Text != ""))
           {
              File.Delete("C:\\Images\\" + lblNewPhoto.Text);
           }
           Response.Redirect("PersonList.aspx");
        }

        public string FormatUsPhone(string num)
        {
           num = Regex.Replace(num, @"[^\d]", "");
           string formatPattern = @"(\d{3})(\d{3})(\d{2})(\d{2})";
           return Regex.Replace(num, formatPattern, "($1) $2-$3-$4");
        }

        public void ShowPersonInfo()
        {
            SqlConnection sqlConnectionToContactsDB = new SqlConnection(_appconfConnString);
            sqlConnectionToContactsDB.Open();
            SqlCommand sqlCommandSelectPersonByID = new SqlCommand("spSelectPersonByID", sqlConnectionToContactsDB);
           sqlCommandSelectPersonByID.CommandType = CommandType.StoredProcedure;
            sqlCommandSelectPersonByID.Parameters.AddWithValue("@PersonID", lblPersonID.Text);
            SqlDataReader personReader;
            personReader = sqlCommandSelectPersonByID.ExecuteReader();

            if (personReader.Read())
            {
                ttFirstName.Text = personReader["FirstName"].ToString();
                ttLastName.Text = personReader["LastName"].ToString();
                ttPhone.Text = FormatUsPhone(personReader["Phone"].ToString()); // REGEX !!!
                ttEmail.Text = personReader["Email"].ToString();
                ttDatePicker.Text = ((DateTime)personReader["Birthday"]).ToString("yyyy.MM.dd");
                if (ttDatePicker.Text == "01.01.1900")
                {
                    ttDatePicker.Text = "";
                }
                lblPath.Text = personReader["Photo"].ToString();
                lblGroupID.Text = personReader["GroupID"].ToString();
            }

            ddGroupList.DataSource = _dataGroups.LoadAllGroups();
            ddGroupList.DataTextField = "GroupName";
            ddGroupList.DataValueField = "GroupID";
            ddGroupList.DataBind();
            ddGroupList.SelectedValue = lblGroupID.Text;

           if (lblPath.Text == "")
           {
              lblPath.Text = "Default.png";
           }

            imgPhoto.ImageUrl = @"GetImage.aspx?file=" + lblPath.Text;

            if (ddGroupList.Text == "")
            {
                lblCheckGroups.Text = "Warning! - Отсутствуют группы!";
                btnSave.Visible = false;
                btnSavePhoto.Visible = false;
                ImageUpload.Visible = false;
                imgPhoto.Visible = false;
            }

            sqlConnectionToContactsDB.Close();
        }

        protected void CustValidNameLengthServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
        {
           if (ttFirstName.Text.Length < 2)
           {
              args.IsValid = false;
           }
           else
           {
              args.IsValid = true;
           }
        }

        protected void CustValidLastNameLengthServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
        {
           if (ttLastName.Text.Length < 2)
           {
              args.IsValid = false;
           }
           else
           {
              args.IsValid = true;
           }
        }

        protected void CustValidPhoneLengthServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
        {
           if (ttPhone.Text == "")
           {
              args.IsValid = true;
           }
           else
           {
              if (ttPhone.Text.Length < 5)
              {
                 args.IsValid = false;
              }

           }
        }



    }
}